import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Text, Image } from '@tarojs/components'
import { AtButton } from 'taro-ui'
import { generateFriendShareImage, generateFriendShareScene } from '@/api/goods/share'
import { getGoodsDetails } from '@/api/goods/details'
import './index.scss'

interface State {
  changeTab: string
  distribution: any
  shareImg: string
  userInfo: any
  goodsInfo: any
}

export default class Share extends Component<any, State> {
  $instance = getCurrentInstance();

  constructor(props) {
    super(props)
    this.state = {
      changeTab: 'one',
      distribution: {},
      shareImg: '',
      userInfo: {},
      goodsInfo: {}
    }
  }

  UNSAFE_componentWillMount() { }
  componentDidMount() {
    const distribution = JSON.parse(this.$instance.router.params.distribution)
    this.getGoodsDetails().then((res) => {
      this.setState({ goodsInfo: res.data.data })
    })
    const userInfo = Taro.getStorageSync('IS_USERINFO')
    this.setState({ changeTab: 'one', distribution, userInfo })
    const data = {
      goodsDistributionId: distribution.goodsDistributionId,
      storeCode: distribution.storeCode,
      goodsId: distribution.id,
      id: distribution.id,
      path: 'pages/goods/details/index',
      mobile: '',
      mobile2: '',
      isStaff: distribution.isStaff,
      isDistribution: distribution.isDistribution,
    }
    // 如果mobile2 等于'' 是一级分销
    if (distribution.mobile2 === '') {
      let IS_USERINFO = Taro.getStorageSync('IS_USERINFO')
      data.mobile = ''
      data.mobile2 = IS_USERINFO.mobile
      console.log('二维码一级',distribution);
    } else if (distribution.mobile === '') {
      // 如果mobile 等于'' 是二级分销
      data.mobile = distribution.mobile1
      data.mobile2 = distribution.mobile2
      console.log('二维码二级',distribution);
    }
    console.log(data);


    this.generateFriendShareScene({ text: data }).then((res => {
      if (res && res.data.success) {
        this.generateFriendShareImage({
          path: 'pages/goods/details/index',
          disShareId: res.data.data.id
        }).then((res) => {
          if (res && res.data.success) {
            this.setState({
              shareImg: res.data.data.url
            })
          }
        })
      }
    }))
  }

  // 商品详情信息
  async getGoodsDetails() {
    const distribution = JSON.parse(this.$instance.router.params.distribution)
    const goodsResult = await getGoodsDetails({
      goodsId: distribution.id,
      storeCode: distribution.storeCode
    })
    return goodsResult
  }

  // 生成分销图片
  async generateFriendShareImage(data) {
    try {
      const res = await generateFriendShareImage(data)
      return res
    } catch (error) {
      console.log(error)
    }
  }

  // 生成分销场景值
  async generateFriendShareScene(data) {
    try {
      const res = await generateFriendShareScene(data)
      return res
    } catch (error) {
      console.log(error)
    }
  }

  // 保存分销图片
  // onLongPress事件
  downloadImg(shareImg) {
    Taro.getSetting({
      success: res => {
        Taro.authorize({
          scope: 'scope.writePhotosAlbum',
          success: res => {
            console.log('授权成功');
            let imgUrl = shareImg;
            console.log(imgUrl);
            Taro.downloadFile({  //下载文件资源到本地，客户端直接发起一个HTTP GET 请求，返回文件的本地临时路径
              url: imgUrl,
              success: res => {
                Taro.saveImageToPhotosAlbum({
                  filePath: res.tempFilePath, //返回的临时文件路径，下载后的文件会存储到一个临时文件
                  success: res => {
                    Taro.showToast({
                      title: '成功保存到相册',
                      icon: 'success'
                    })
                  }
                })
              }
            })
          }
        })
      }
    })
  }

  onShareAppMessage() {
    const { distribution, userInfo, goodsInfo } = this.state
    let params = `id=${distribution.id}&storeCode=${distribution.storeCode}&shareType=${distribution.shareType}&goodsDistributionId=${distribution.goodsDistributionId}&isDistribution=${distribution.isDistribution}&isStaff=${distribution.isStaff}`
    // 如果mobile2 等于'' 是一级分销
    if (distribution.mobile2 === '') {
      let IS_USERINFO = Taro.getStorageSync('IS_USERINFO')
      params += `&mobile=&mobile2=${IS_USERINFO.mobile}`
      console.log('一级');
    }// 如果mobile 等于'' 是二级分销
    else if (distribution.mobile === '') {
      console.log('二级');
      params += `&mobile=${distribution.mobile1}&mobile2=${distribution.mobile2}`
    }
    console.log(distribution);
    console.log(params)
    let path = `/pages/goods/details/index?${params}`
    return {
      title: goodsInfo.goodsName,
      path,
      imageUrl: goodsInfo.imageInfo.thumbnail.url
    }
  }

  // 分享好友
  shareFriend() {
    const { goodsInfo } = this.state
    return (
      <View className="share-module">
        <View className="share-content">
          <View className="share-title">
            <View className="head-portrait"></View>
            <View className="share-main">
              <View className="company-name">集群车宝 | 机油保养洗车轮胎</View>
              <View className="goods-name">{goodsInfo.goodsName}</View>
              <View className="goods-img">
								{goodsInfo?.imageInfo?.wheel[0]?.url ? <Image className="goods-img" src={goodsInfo.imageInfo.wheel[0].url} /> : null}
              </View>
            </View>
          </View>
        </View>
        <View className="share-hint">
          <View>提示： </View>
          <View>分享专属链接到微信好友聊天，好友购买可获直接奖励，好友分享你的链接给其他客户可获间接奖励。</View>
        </View>
        <View className="save-image">
          <AtButton type='primary' openType='share'>分享给微信好友</AtButton>
        </View>
      </View>
    )
  }
  // 分享朋友圈
  shareFriendsCircle() {
    const { distribution, shareImg } = this.state
    return (
      <View className="share-module">
        <View className="share-content">
          <View className="share-title">
            <View className="head-portrait"></View>
            <View className="head-text">{distribution.text}</View>
          </View>
          <View className="share-img">
            <Image src={shareImg}></Image>
          </View>
        </View>
        <View className="share-hint">
          <View>提示： </View>
          <View>点击分享素材，图片自动保存到相册，打开手机相册，到朋友圈分享你的专属海报。</View>
        </View>
        <View className="save-image">
          <AtButton type='primary' onClick={() => { this.downloadImg(shareImg) }}>保存图片</AtButton>
        </View>
      </View>
    )
  }

  render() {
    const { changeTab, distribution } = this.state
    return (
      <View className="share-page">
        <View className="hint"><Text>推广成功可得佣金</Text><Text className="price">￥{distribution.directlyCommissionPrice}</Text></View>
        <View className="share-Btns">
          <View className={`btn ${changeTab === 'one' ? 'btn-pitch' : ''}`} onClick={() => { this.setState({ changeTab: 'one' }) }}>分享给微信好友</View>
          <View className={`btn ${changeTab === 'two' ? 'btn-pitch' : ''}`} onClick={() => { this.setState({ changeTab: 'two' }) }}>分享到朋友圈</View>
        </View>
        <View>
          {changeTab === 'one' ? this.shareFriend() : this.shareFriendsCircle()}
        </View>
      </View>
    )
  }
}
